package com.demo.alternate_exchange;

import com.demo.commons.MqCons;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 备份交换机配置, 架构图看 docs/images/AlternateExchange.png
 * @author shenguangyang
 */
@Configuration
public class AlternateExchangeConfig {
    /**
     * 声明确认队列
     */
    @Bean("confirmQueue")
    public Queue confirmQueue() {
        return QueueBuilder.durable(MqCons.CONFIRM_QUEUE).build();
    }
    /**
     * 声明确认队列绑定关系
     */
    @Bean
    public Binding queueBinding(@Qualifier("confirmQueue") Queue queue,
                                @Qualifier("confirmExchange") DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("key1");
    }
    /**
     * 声明确认 Exchange 交换机的备份交换机
     */
    @Bean("confirmExchange")
    public DirectExchange confirmExchange() {
        ExchangeBuilder exchangeBuilder = ExchangeBuilder.directExchange(MqCons.CONFIRM_EXCHANGE)
                        .durable(true)
                        // 设置该交换机的备份交换机
                        .withArgument("alternate-exchange", MqCons.BACKUP_EXCHANGE);
        return exchangeBuilder.build();
    }


    /**
     * 声明备份 Exchange
     */
    @Bean("backupExchange")
    public FanoutExchange backupExchange() {
        return new FanoutExchange(MqCons.BACKUP_EXCHANGE);
    }
    // 声明警告队列
    @Bean("warningQueue")
    public Queue warningQueue(){
        return QueueBuilder.durable(MqCons.WARNING_QUEUE).build();
    }

    // 声明报警队列绑定关系
    @Bean
    public Binding warningBinding(@Qualifier("warningQueue") Queue queue,
                                  @Qualifier("backupExchange") FanoutExchange
                                          backupExchange){
        return BindingBuilder.bind(queue).to(backupExchange);
    }

    /**
     * 声明备份队列
     */
    @Bean("backQueue")
    public Queue backQueue(){
        return QueueBuilder.durable(MqCons.BACKUP_QUEUE).build();
    }

    /**
     * 声明备份队列绑定关系
     */
    @Bean
    public Binding backupBinding(@Qualifier("backQueue") Queue queue,
                                 @Qualifier("backupExchange") FanoutExchange backupExchange){
        return BindingBuilder.bind(queue).to(backupExchange);
    }
}
